package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.MyReportDto
import cn.exrick.xboot.base.entity.MyReport
import cn.exrick.xboot.base.mapper.MyReportMapper
import cn.exrick.xboot.base.service.IEnterpriseUserService
import cn.exrick.xboot.base.service.IMyReportService
import cn.exrick.xboot.base.vo.MyReportDetailVo
import cn.exrick.xboot.base.vo.MyReportVo
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.service.UserService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*

/**
 * 我的上报接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IMyReportServiceImpl : ServiceImpl<MyReportMapper?, MyReport?>(), IMyReportService {


    @Autowired
    private lateinit var securityUtil: SecurityUtil

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var iEnterpriseUserService: IEnterpriseUserService

    override fun createReport(myReport: MyReport): Result<Any?>? {

        return try {
            saveOrUpdate(myReport)
            ResultUtil.success("上报成功")
        }catch (e: Exception) {
            ResultUtil.error(e.message)
        }
    }

    override fun removeReport(id: String): Result<Any?>? {

        return try {
            removeById(id)
            ResultUtil.success("移除成功")
        }catch (e: Exception) {
            ResultUtil.error(e.message)
        }
    }

    override fun getMyReportList(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(MyReport::class.java).eq(MyReport::createBy, securityUtil.currUser.id)
                .orderByDesc(MyReport::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { MyReportVo().apply { ToolUtil.copyProperties(this, it) } }.toMutableList())

            ResultUtil.data(result, "获取我的上报列表成功！")
        } ?: ResultUtil.error(201, "暂无数据")
    }

    override fun getMyReportDetail(id: String): Result<MyReportDetailVo>? {

        return getMyReportDetailFun(id)?.run { ResultUtil.data(this, "获取上报详情成功！") } ?: ResultUtil.error(201, "数据不存在！")
    }

    override fun getSupervisionPreCheckRePort(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

         return ToolUtil.setListToNul(list(KtQueryWrapper(MyReport::class.java).isNull(MyReport::actualCheckUserId)
               .orderByDesc(MyReport::createTime)))?.run {

            val data = ToolUtil.setListToNul(filter {
                it?.checkUserIds?.split(",")?.contains(securityUtil.currUser.id)!!
            }.mapNotNull { MyReportVo().apply { ToolUtil.copyProperties(it, this) } }.toMutableList())

             if (ToolUtil.isNotEmpty(data)) {

                 val result:MutableMap<String, Any?> = Maps.newHashMap()
                 result["size"] = data.size
                 result["content"] = PageUtil.listToPage(pageVo, data)
                 return@run ResultUtil.data(result, "获取数据成功！")
             }else {

                 return ResultUtil.error(201, "暂无数据")
             }

         } ?: ResultUtil.error(201, "暂无数据！")
    }

    override fun getSupervisionHaveCheckReport(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return ToolUtil.setListToNul(list(KtQueryWrapper(MyReport::class.java).eq(MyReport::actualCheckUserId, securityUtil.currUser.id)
                .orderByDesc(MyReport::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull { MyReportVo().apply { ToolUtil.copyProperties(it, this) } }.toMutableList())

            ResultUtil.data(result, "获取我的上报列表成功！")
        } ?: ResultUtil.error(201, "暂无数据")
    }

    override fun resolveReport(myReportDto: MyReportDto): Result<Any?>? {

        return try {

            getById(myReportDto.id)?.run {

                updateById(this.apply {

                    actualCheckUserId = securityUtil.currUser.id
                    checkTime = Date()
                })

                ResultUtil.success("操作成功!")
            }
        } catch (e : Exception) {

            ResultUtil.error(e.message)
        }
    }


    /**
     * 获取上报详情信息(封装类)
     */
    private fun getMyReportDetailFun(id: String): MyReportDetailVo? {

        return getById(id)?.run {

            MyReportDetailVo().apply {

                ToolUtil.copyProperties(this@run, this)
                reportUser = if (anonymity!!) "匿名" else userService.get(createBy)?.nickname
                pics = this@run.pics?.split(",")
                enterpriseName = iEnterpriseUserService.getEnterpriseNameById(enterpriseUserId)
                typeStr = when (type) {

                    1 -> {
                        "事故隐患"
                    }
                    2 -> {
                        "举报"
                    }
                    3 -> {
                        "安全建议"
                    }
                    else -> {
                        "提醒"
                    }
                }
                checkUser = checkUserIds?.split(",")?.map { userId ->

                    userService.get(userId)?.let {

                        val data:MutableMap<String, Any?> = Maps.newHashMap()
                        data["nickname"] = it.nickname
                        data["avatar"] = it.avatar
                        data["userId"] = it.id
                        data
                    }
                }?.toMutableList()
                actualCheckUser = actualCheckUserId?.let { userService.get(it)?.nickname }
            }
        }
    }

}